// MyNFT.sol 快速部署脚本
// 使用方法: node quick-deploy.js

const { ethers } = require('ethers');
require('dotenv').config();

// 部署配置
const DEPLOY_CONFIG = {
    // NFT基本信息
    name: "MyLearningNFT",
    symbol: "MLN",
    baseURI: "ipfs://",
    maxSupply: 1000,
    maxMintPerAddress: 10,

    // 网络配置
    rpcUrl: process.env.SEPOLIA_RPC_URL || "https://sepolia.infura.io/v3/YOUR_INFURA_PROJECT_ID",
    privateKey: process.env.PRIVATE_KEY,

    // Gas配置
    gasLimit: 5000000,
    gasPrice: ethers.utils.parseUnits('20', 'gwei')
};

// 简化的合约ABI（仅包含部署和基本功能）
const CONTRACT_ABI = [
    "constructor(string memory _name, string memory _symbol, string memory _initialBaseURI, uint256 _maxSupply, uint256 _maxMintPerAddress)",
    "function name() public view returns (string)",
    "function symbol() public view returns (string)",
    "function totalSupply() public view returns (uint256)",
    "function owner() public view returns (address)",
    "function mintNFT(address to, string memory _tokenURI) public payable returns (uint256)",
    "function tokenURI(uint256 tokenId) public view returns (string)",
    "function ownerOf(uint256 tokenId) public view returns (address)",
    "function balanceOf(address owner) public view returns (uint256)",
    "function tokensOfOwner(address owner) public view returns (uint256[])",
    "function maxSupply() public view returns (uint256)",
    "function maxMintPerAddress() public view returns (uint256)",
    "function mintedCount(address) public view returns (uint256)",
    "function setBaseURI(string memory newBaseURI) public",
    "function updateConfig(uint256 _maxSupply, uint256 _maxMintPerAddress, uint256 _mintPrice, bool _publicMintEnabled) public",
    "event NFTMinted(address indexed to, uint256 indexed tokenId, string tokenURI)",
    "event ConfigUpdate(uint256 maxSupply, uint256 maxMintPerAddress, uint256 mintPrice, bool publicMintEnabled)"
];

// 合约字节码 - 请替换为实际编译后的字节码
const CONTRACT_BYTECODE = `
请将编译后的MyNFT.sol字节码粘贴到这里
使用命令: npx solc --bin --include-path node_modules --base-path . MyNFT.sol
`;

async function quickDeploy() {
    try {
        console.log("🚀 开始快速部署MyNFT合约...\n");

        // 检查环境变量
        if (!DEPLOY_CONFIG.privateKey) {
            throw new Error("❌ 请设置PRIVATE_KEY环境变量");
        }

        // 连接网络
        const provider = new ethers.providers.JsonRpcProvider(DEPLOY_CONFIG.rpcUrl);
        const wallet = new ethers.Wallet(DEPLOY_CONFIG.privateKey, provider);

        console.log("📡 网络信息:");
        console.log("- 网络:", (await provider.getNetwork()).name);
        console.log("- 部署地址:", wallet.address);
        console.log("- 余额:", ethers.utils.formatEther(await wallet.getBalance()), "ETH\n");

        // 检查字节码
        if (CONTRACT_BYTECODE.includes("请将编译后的")) {
            console.log("⚠️  请先编译合约并更新字节码！");
            console.log("运行命令: npx solc --bin --include-path node_modules --base-path . MyNFT.sol");
            return;
        }

        // 创建合约工厂
        const contractFactory = new ethers.ContractFactory(
            CONTRACT_ABI,
            CONTRACT_BYTECODE,
            wallet
        );

        console.log("🎨 部署参数:");
        console.log("- 名称:", DEPLOY_CONFIG.name);
        console.log("- 符号:", DEPLOY_CONFIG.symbol);
        console.log("- 基础URI:", DEPLOY_CONFIG.baseURI);
        console.log("- 最大供应量:", DEPLOY_CONFIG.maxSupply);
        console.log("- 每地址最大铸造:", DEPLOY_CONFIG.maxMintPerAddress, "\n");

        // 部署合约
        console.log("⏳ 正在部署合约...");
        const contract = await contractFactory.deploy(
            DEPLOY_CONFIG.name,
            DEPLOY_CONFIG.symbol,
            DEPLOY_CONFIG.baseURI,
            DEPLOY_CONFIG.maxSupply,
            DEPLOY_CONFIG.maxMintPerAddress,
            {
                gasLimit: DEPLOY_CONFIG.gasLimit,
                gasPrice: DEPLOY_CONFIG.gasPrice
            }
        );

        console.log("🔄 等待交易确认...");
        console.log("- 交易哈希:", contract.deployTransaction.hash);

        await contract.deployed();

        console.log("\n✅ 合约部署成功!");
        console.log("- 合约地址:", contract.address);
        console.log("- 区块号:", contract.deployTransaction.blockNumber);

        // 验证部署
        console.log("\n🔍 验证合约信息:");
        const name = await contract.name();
        const symbol = await contract.symbol();
        const totalSupply = await contract.totalSupply();
        const owner = await contract.owner();

        console.log("- NFT名称:", name);
        console.log("- NFT符号:", symbol);
        console.log("- 当前供应量:", totalSupply.toString());
        console.log("- 合约所有者:", owner);

        // 保存部署信息
        const deploymentInfo = {
            contractAddress: contract.address,
            deploymentHash: contract.deployTransaction.hash,
            deploymentBlock: contract.deployTransaction.blockNumber,
            deployer: wallet.address,
            network: "sepolia",
            timestamp: new Date().toISOString(),
            config: DEPLOY_CONFIG
        };

        require('fs').writeFileSync(
            'deployment-info.json',
            JSON.stringify(deploymentInfo, null, 2)
        );

        console.log("\n📄 部署信息已保存到 deployment-info.json");

        // 生成链接
        console.log("\n🔗 相关链接:");
        console.log("- Etherscan:", `https://sepolia.etherscan.io/address/${contract.address}`);
        console.log("- OpenSea:", `https://testnets.opensea.io/assets/sepolia/${contract.address}`);

        console.log("\n🎉 部署完成！现在可以开始铸造NFT了！");

        return contract;

    } catch (error) {
        console.error("❌ 部署失败:", error.message);
        throw error;
    }
}

// 快速测试函数
async function quickTest(contractAddress) {
    try {
        console.log("\n🧪 开始快速功能测试...");

        const provider = new ethers.providers.JsonRpcProvider(DEPLOY_CONFIG.rpcUrl);
        const wallet = new ethers.Wallet(DEPLOY_CONFIG.privateKey, provider);
        const contract = new ethers.Contract(contractAddress, CONTRACT_ABI, wallet);

        // 基础信息测试
        console.log("1️⃣ 基础信息:");
        const name = await contract.name();
        const symbol = await contract.symbol();
        const totalSupply = await contract.totalSupply();
        console.log("✅ 名称:", name);
        console.log("✅ 符号:", symbol);
        console.log("✅ 总供应量:", totalSupply.toString());

        // 铸造测试
        console.log("\n2️⃣ 铸造测试:");
        const testMetadataURI = "ipfs://QmTestHash";
        const tx = await contract.mintNFT(wallet.address, testMetadataURI);
        const receipt = await tx.wait();
        const tokenId = receipt.events?.find(e => e.event === 'NFTMinted')?.args?.tokenId;

        console.log("✅ 铸造成功，Token ID:", tokenId.toString());

        // 查询测试
        console.log("\n3️⃣ 查询测试:");
        const owner = await contract.ownerOf(tokenId);
        const balance = await contract.balanceOf(wallet.address);
        const tokenURI = await contract.tokenURI(tokenId);

        console.log("✅ Token所有者:", owner);
        console.log("✅ 地址余额:", balance.toString());
        console.log("✅ Token URI:", tokenURI);

        console.log("\n🎉 所有测试通过！合约功能正常！");

    } catch (error) {
        console.error("❌ 测试失败:", error.message);
    }
}

// 主函数
async function main() {
    const args = process.argv.slice(2);

    if (args[0] === 'test' && args[1]) {
        // 测试模式
        await quickTest(args[1]);
    } else {
        // 部署模式
        const contract = await quickDeploy();
        if (contract) {
            console.log("\n💡 要测试合约功能，运行:");
            console.log(`node quick-deploy.js test ${contract.address}`);
        }
    }
}

// 运行脚本
if (require.main === module) {
    main().catch(console.error);
}

module.exports = { quickDeploy, quickTest, DEPLOY_CONFIG };
